<template>
	<div>
		<Particles id="tsparticles" :particlesInit="particlesInit" :particlesLoaded="particlesLoaded" :options="particles" />

		<div class="formContainer">
			<h3>企业管理系统</h3>
			<!-- form start -->
			<el-form ref="loginFormRef" :model="loginForm" status-icon :rules="loginRules" label-width="120px"
				class="demo-ruleForm">
				<!-- 用户名 -->
				<el-form-item label="用户名" prop="username">
					<el-input type="username" autocomplete="off" v-model="loginForm.username" />
				</el-form-item>

				<!-- 用户密码 -->
				<el-form-item label="用户密码" prop="password">
					<el-input type="password" autocomplete="off" v-model="loginForm.password" />
				</el-form-item>

				<!-- 登录按钮 -->
				<el-form-item>
					<el-button class="loginButton" type="primary" @click="submitForm()">登录</el-button>
				</el-form-item>
			</el-form>
			<!-- form end -->
		</div>
	</div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useStore } from 'vuex'
const store = useStore()
// 引入粒子动画
import { loadFull } from "tsparticles"
import { particles } from "../components/particles/particles.js"

import { ElMessage } from 'element-plus'

// 表单引用对象（从vue中导进来的）拿到引用对象，做手动校验
const loginFormRef = ref()

// 表单绑定响应式对象
const loginForm = reactive({
	username: "",
	password: ""
})

// 表单验证规则（失去焦点验证规则）
const loginRules = reactive({
	username: [
		{
			required: true,
			message: '请输入用户名',
			trigger: 'blur'
		}
	],
	password: [
		{
			required: true,
			message: '请输入用密码',
			trigger: 'blur'
		}
	]
})

const router = useRouter()
/**
 * 登录函数，提交表单函数
 */
const submitForm = () => {
	// 1. 校验表单，loginFormRef.value.validate((valid)触发手动校验
	loginFormRef.value.validate((valid) => {
		if (valid) {
			axios.post("/adminapi/user/login", loginForm).then(res => {
				if (res.data.status !== 0) {
					return ElMessage.error('用户登录失败，请稍后重试！')
				}
				store.commit("changeUserInfo", res.data.data)
				store.commit('changeGetterRouter', false)
				ElMessage.success('登录成功！')
				router.push("/index")
			})
		} else {
			// 验证不通过
			return false
		}
	})
}

// 粒子动画
const particlesInit = async engine => {
	await loadFull(engine)
}
const particlesLoaded = async container => {
	console.log("Particles container loaded", container)
}
</script>

<style lang="scss" scoped>
.formContainer {
	width: 500px;
	height: 300px;
	position: fixed;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	background: rgba($color: #000000, $alpha: 0.2);
	color: white;
	text-align: center;
	padding: 30px;
}

// v-deep 是vue中的深度选择
::v-deep .el-form-item__label {
	color: white;
	font-size: 18px;
}

.loginButton {
	width: 100px;
	height: 32px;
	// font-size: 18px;
}

h3 {
	font-size: 30px;
	font-weight: normal;
	margin-bottom: 20px;
}
</style>